package edu.pku.sei.modeler.neditor.action;

import org.eclipse.gef.editparts.AbstractEditPart;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPart;

import edu.pku.sei.modeler.model.common.AbstractPackage;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.core.MetaElement;
import edu.pku.sei.modeler.model.notation.shape.TextObject;
import edu.pku.sei.modeler.neditor.dialog.AttributeMappingDialog;
import edu.pku.sei.modeler.neditor.model.Diagram;
import edu.pku.sei.modeler.neditor.ui.NotationEditor;

public class MappingAttributeAction extends SelectionAction {
	static final public String MAPPING_ATTRIBUTE_ID = "MAPPING_ATTRIBUTE_ID";

	public MappingAttributeAction(IWorkbenchPart part) {
		super(part);
		setText("Mapping Attribute");
		setId(MAPPING_ATTRIBUTE_ID);
	}
	protected AttributeMappingDialog dlg = null;
	@Override
	public void run() {
		IStructuredSelection s = (IStructuredSelection)this.getSelection();
		Diagram diagram = ((NotationEditor)getWorkbenchPart()).getDiagram();
		MetaElement element = null;
		try {
			AbstractPackage pkg = ModelRegistry.getRegistry().getPakcageByModel(diagram.getModel());
			element = pkg.getObjByID(diagram.getNotation().getModelID());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(element==null){
			MessageDialog.openError(null,"Error", "the abstract syntax model is null");
			return;
		}
		if(dlg==null) dlg  = new AttributeMappingDialog((Shell)null);
		
		dlg.inputElement = element;
		
		if(dlg.open()==Window.OK) {
			Object abs = s.getFirstElement();
			Object model = ((AbstractEditPart)abs).getModel();
			if(model instanceof TextObject) {
				((TextObject)model).setTextMapping(dlg.result);
			}
			return;
		}
	}

	@Override
	protected boolean calculateEnabled() {
		IStructuredSelection s = (IStructuredSelection)this.getSelection();
		if(s.getFirstElement()!=null) {
			if(s.getFirstElement() instanceof AbstractEditPart) {
				Object model = ((AbstractEditPart)s.getFirstElement()).getModel();
				if(model.getClass()==TextObject.class) {
					return true;
				}
			}
		}
		return false;
	}
}

